<template>
  <!-- 其他燃料用量 -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="使用时间">
        <el-date-picker
          v-model="daterangeDt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="燃料类型" prop="fuelType">
        <el-select v-model="queryParams.fuelType" placeholder="请选择燃料类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.other_fuel_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bm:OtherFuelData:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bm:OtherFuelData:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bm:OtherFuelData:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bm:OtherFuelData:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="OtherFuelDataList" @selection-change="handleSelectionChange" 
              :show-summary="true" :summary-method="getSummaries" @sort-change="handleSortChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" width="55" />
      <el-table-column label="使用时间" align="center" prop="dt" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="燃料类型" align="center" prop="fuelType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.other_fuel_type" :value="scope.row.fuelType"/>
        </template>
      </el-table-column>
      <el-table-column label="使用量" align="center" prop="val" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseFloat(scope.row.val).toFixed(3) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.other_fuel_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="记录人" align="center" prop="recordPerson" />
      <el-table-column label="校验人" align="center" prop="checkPerson" />
      <el-table-column label="厂区" align="center" prop="factory" />
      <el-table-column label="票据" align="center" prop="fileUrl">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.fileUrl"
            :src="scope.row.fileUrl" 
            :preview-src-list="[scope.row.fileUrl]"
            style="max-width: 50px; max-height: 50px; object-fit: contain;"
          ></el-image>
          <span v-else>暂无票据</span>
        </template>
      </el-table-column>
      
      <el-table-column label="录入时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bm:OtherFuelData:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bm:OtherFuelData:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改其他燃料用量对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用时间" prop="dt">
              <el-date-picker clearable
                v-model="form.dt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择使用时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="燃料类型" prop="fuelType">
              <el-select v-model="form.fuelType" placeholder="请选择燃料类型">
                <el-option
                  v-for="dict in dict.type.other_fuel_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用量" prop="val">
              <el-input-number 
                v-model="form.val" 
                placeholder="请输入使用量" 
                :precision="3"
                :step="0.001"
                :min="0"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option
                  v-for="dict in dict.type.other_fuel_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录人" prop="recordPerson">
              <el-input v-model="form.recordPerson" placeholder="请输入记录人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="校验人" prop="checkPerson">
              <el-input v-model="form.checkPerson" placeholder="请输入校验人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂区" prop="factory">
              <el-select v-model="form.factory" placeholder="请选择厂区">
                <el-option
                  v-for="dict in dict.type.company_dict"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="票据" prop="fileUrl">
              <div class="upload-container">
                <!-- 上传前显示上传区域 -->
                <el-upload
                  v-if="!form.fileUrl"
                  class="upload-area"
                  action="/dev-api/common/uploadMinio"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeImageUpload"
                >
                  <i class="el-icon-plus upload-icon"></i>
                  <div class="upload-text">点击上传票据</div>
                </el-upload>
                
                <!-- 上传后显示图片和删除按钮 -->
                <div v-else class="image-preview">
                  <img :src="form.fileUrl" class="preview-image" />
                  <div class="image-actions">
                    <i class="el-icon-delete delete-icon" @click="handleImageDelete"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOtherFuelData, getOtherFuelData, delOtherFuelData, addOtherFuelData, updateOtherFuelData } from "@/api/mes/bm/OtherFuelData";
import { getToken } from "@/utils/auth";
import { mapGetters } from 'vuex';

export default {
  name: "OtherFuelData",
  dicts: ['other_fuel_type', 'other_fuel_unit', 'company_dict'],
  computed: {
    ...mapGetters([
      'nickName'
    ])
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 其他燃料用量表格数据
      OtherFuelDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标识时间范围
      daterangeDt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginDt: undefined,
        endDt: undefined,
        fuelType: undefined,
        dtSortFlag: 0,    // 使用时间排序标志
        valSortFlag: 0    // 使用量排序标志
      },
      // 表单参数
      form: {},
      // HTTP请求头
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 表单校验
      rules: {
        dt: [
          { required: true, message: "使用时间不能为空", trigger: "blur" }
        ],        fuelType: [
          { required: true, message: "燃料类型不能为空", trigger: "change" }
        ],        val: [
          { required: true, message: "使用量不能为空", trigger: "blur" },
          { type: 'number', message: "使用量必须为数字", trigger: "blur" },
          { validator: this.validateNumericInput, trigger: "blur" }
        ],        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],        recordPerson: [
          { required: true, message: "记录人不能为空", trigger: "blur" }  
        ],        factory: [
          { required: true, message: "厂区不能为空", trigger: "blur" }
        ]  
      },
      resetKey: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 计算表格的总计行 */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if (column.property === 'val') {
          const values = data.map(item => Number(item.val));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + value;
              } else {
                return prev;
              }
            }, 0).toFixed(3);
          } else {
            sums[index] = 'N/A';
          }
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    /** 查询其他燃料用量列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDt && '' != this.daterangeDt) {
        this.queryParams.params["beginDt"] = this.daterangeDt[0];
        this.queryParams.params["endDt"] = this.daterangeDt[1];
      }
      listOtherFuelData(this.queryParams).then(response => {
        this.OtherFuelDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dt: null,
        fuelType: null,
        val: 0.000,
        unit: null,
        recordPerson: null,
        checkPerson: null,
        factory: null,
        fileUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.daterangeDt = [];
      this.queryParams.beginDt = undefined;
      this.queryParams.endDt = undefined;
      this.queryParams.dtSortFlag = 0;
      this.queryParams.valSortFlag = 0;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 设置默认记录人
      this.form.recordPerson = this.nickName;
      
      // 设置默认使用时间为前一天
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      const year = yesterday.getFullYear();
      const month = String(yesterday.getMonth() + 1).padStart(2, '0');
      const day = String(yesterday.getDate()).padStart(2, '0');
      this.form.dt = `${year}-${month}-${day}`;
      
      // 如果存在数据，则使用最新一条记录的燃料类型、单位、厂区信息
      if (this.OtherFuelDataList && this.OtherFuelDataList.length > 0) {
        // 获取最新一条记录（假设列表已按时间排序，第一条是最新的）
        const latestRecord = this.OtherFuelDataList[0];
        
        // 设置默认值
        this.form.fuelType = latestRecord.fuelType;
        this.form.unit = latestRecord.unit;
        this.form.factory = latestRecord.factory;
        
        // 如果希望也使用最新记录的记录人和校验人
        // this.form.recordPerson = latestRecord.recordPerson;
        this.form.checkPerson = latestRecord.checkPerson;
      }
      
      this.open = true;
      this.title = "添加其他燃料用量";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOtherFuelData(id).then(response => {
        this.form = response.data;
        if (this.form.fileUrl) {
          if (this.form.fileUrl.indexOf('http') !== 0 && this.form.fileUrl.indexOf('https') !== 0) {
            this.form.fileUrl = process.env.VUE_APP_BASE_API + this.form.fileUrl;
          }
          this.form.evidenceFile = [this.form.fileUrl];
        } else {
          this.form.evidenceFile = [];
        }
        this.open = true;
        this.title = "修改其他燃料用量";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建要提交的数据对象
          const submitData = {...this.form};
          
          // 如果图片已删除，确保相关字段为null
          if (!submitData.fileUrl) {
            submitData.fileUrl = null;
            submitData.fileName = null;
            submitData.evidenceFile = [];
          }
          
          if (submitData.id != null) {
            updateOtherFuelData(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOtherFuelData(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除其他燃料用量编号为"' + ids + '"的数据项？').then(function() {
        return delOtherFuelData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const timestamp = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      
      this.download('mes/bm/OtherFuelData/export', {
        ...this.queryParams
      }, `其他燃料用量_${timestamp}.xlsx`)
    },
    /** 图片上传成功处理 */
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        const fileUrl = response.url;
        // 确保URL格式正确
        this.form.fileUrl = fileUrl.indexOf('http') === 0 ? fileUrl : process.env.VUE_APP_BASE_API + fileUrl;
        // 提取文件名
        const fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
        this.form.fileName = fileName;
        this.form.evidenceFile = [fileUrl];
        
        this.$message.success('票据上传成功');
        console.log("图片上传成功：", this.form.fileUrl, this.form.fileName);
      } else {
        this.$message.error('票据上传失败');
      }
    },
    
    /** 处理图片删除 */
    handleImageDelete() {
      this.$confirm('确认删除已上传的票据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清空所有相关字段
        this.form.fileUrl = null;
        this.form.fileName = null;
        this.form.evidenceFile = [];
        
        this.$message.success('票据已删除');
        console.log("图片已删除，相关字段已清空");
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    /** 验证数字输入 */
    validateNumericInput(rule, value, callback) {
      if (value === '' || value === null || value === undefined) {
        callback();
        return;
      }
      if (isNaN(Number(value))) {
        callback(new Error('请输入有效的数字'));
        return;
      }
      callback();
    },
    
    /** 输入时验证并转换数字 */
    validateNumber(val) {
      // 如果输入不是数字，则清空或保留上一个有效值
      if (val === '' || isNaN(Number(val))) {
        this.form.val = '';
      } else {
        // 确保是数字类型
        this.form.val = Number(val);
      }
    },
    
    /** 上传前图片验证 */
    beforeImageUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    /** 处理表格排序变化 */
    handleSortChange(column) {
      // 首先将所有排序标志重置为0
      this.queryParams.dtSortFlag = 0;
      this.queryParams.valSortFlag = 0;
      
      // 然后根据当前排序列设置对应的排序标志
      if (column.prop === "dt") {
        if (column.order === "ascending") {
          this.queryParams.dtSortFlag = 1;
        } else if (column.order === "descending") {
          this.queryParams.dtSortFlag = -1;
        }
      } else if (column.prop === "val") {
        if (column.order === "ascending") {
          this.queryParams.valSortFlag = 1;
        } else if (column.order === "descending") {
          this.queryParams.valSortFlag = -1;
        }
      }
      this.getList();
    },
  }
};
</script>

<style scoped>
.upload-container {
  width: 100%;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 178px;
  height: 178px;
  cursor: pointer;
  position: relative;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
  margin-top: 8px;
}

.image-preview {
  position: relative;
  width: 178px;
  height: 178px;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-actions {
  position: absolute;
  top: 0;
  right: 0;
  padding: 8px;
  background-color: rgba(0, 0, 0, 0.5);
  border-bottom-left-radius: 6px;
}

.delete-icon {
  font-size: 16px;
  color: #fff;
  cursor: pointer;
}

.delete-icon:hover {
  color: #f56c6c;
}
</style>
